import { Modal, Spin } from "antd";
import "./style.less";

// showLoading的参数类型
interface loadingConfig {
  from: string;
  text: string;
}

// 字面量类型
type modalType = "error" | "confirm" | "warning" | "success" | "info";

// showModal的参数类型
interface modalConfig {
  title?: string;
  content?: string;
  okText?: string;
  onOk?: () => void;
}

/**
 * 统计有多少个loading请求
 */
const loadingCount = (function () {
  let count = 0;
  return {
    add(): number {
      count += 1;
      return count;
    },
    reduce(): number {
      count && (count -= 1);
      return count;
    },
  };
})();

let spinModal: any;

export function showLoading(config: loadingConfig) {
  // 请求数+1
  loadingCount.add();
  const content = {
    className: "spin",
    content: <Spin tip={config?.text ?? "加载中..."} />,
  };
  // 显示loading
  if (!spinModal) {
    spinModal = Modal.info(content);
  } else {
    spinModal.update(content);
  }
}

export function hideLoading() {
  // 所有使用了全局loading的请求完成后才消失
  if (loadingCount.reduce() === 0) {
    // 避免网速太快造成闪屏，这里延迟200ms后才销毁
    setTimeout(() => {
      spinModal.destroy();
    }, 200);
  }
}

export function reLoading() {
  Modal.warn({
    className: "tips re-loading",
    title: "系统消息",
    content: "您还未登陆或登陆已过期，点击后重新登陆",
    onOk() {
      window.location.href = `/login?redirect=${window.location.pathname}`;
    },
    okText: "登陆",
  });
}

export function ajaxError<T = string>(message: T[]) {
  Modal.warn({
    className: "tips ajax-error",
    title: "系统消息",
    content: message.map((item, index) => <div key={index}>{item}</div>),
  });
}

export function Warn<T = string>(content: T[]) {
  Modal.warn({
    className: "tips component-warn",
    title: "系统消息",
    content: content.map((item, index) => <div key={index}>{item}</div>),
  });
}

export function confirmLogin<T = string>(
  message: T[],
  onOk: (...args: any[]) => any
) {
  Modal.warn({
    className: "tips ajax-error",
    title: "系统消息",
    content: message.map((item, index) => <div key={index}>{item}</div>),
    onOk,
  });
}

export default {
  warn: Warn,
};
